-module(tracer).
-behaviour(gen_server).

%% gen_server exports
-export([init/1, handle_cast/2, handle_call/3, terminate/2]).

%% client interface
-export([start_link/0, start_trace/3, stop/1]).

%% Start tracing
start_trace(Pid, Pos, Size) ->
   gen_server:cast(Pid, {start, Pos, Size}).

%% Start a worker
stop(Pid) ->
    gen_server:call(Pid, stop).


init([]) ->
    Scene = scene:get(),
    {ok, Scene}.

start_link() ->
    {ok, Pid} = gen_server:start_link(tracer, [], []),
    trace_manager:register(Pid),
    {ok, Pid}.

handle_cast({start, Pos, Size}, Scene) ->
    {X, Y} = Pos,
    Color = trace:start(Pos, Size, Scene),
    Pixel = {X, Y, Color},
    
    trace_manager:pixel(Pixel),
    trace_manager:finished(self()),
    {noreply, Scene}.


handle_call(stop, _From, Scene) ->
    {stop, shutdown, ok, Scene}.

terminate(shutdown, _Scene) -> ok.